"use client";

import React, { forwardRef } from "react";
import { Card, Typography, Spin } from "antd";
import ReactMarkdown from "react-markdown";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { vscDarkPlus } from "react-syntax-highlighter/dist/cjs/styles/prism";
import rehypeRaw from "rehype-raw";
import remarkGfm from "remark-gfm";

const { Title, Text } = Typography;

interface PreviewContentProps {
  title?: string;
  content: string;
  type?: "markdown" | "html";
  taskTitle?: string;
  stepNumber?: number;
  totalSteps?: number;
  isLoading?: boolean;
  className?: string;
  id?: string;
}

const PreviewContent = forwardRef<HTMLDivElement, PreviewContentProps>(
  (
    {
      title,
      content,
      type = "markdown",
      taskTitle,
      stepNumber,
      totalSteps,
      isLoading = false,
      className = "",
      id,
    },
    ref
  ) => {
    // 提取标题，用于生成目录
    const extractHeadings = (content: string) => {
      const headingRegex = /^(#{1,6})\s+(.+)$/gm;
      const headings = [];
      let match;
      
      while ((match = headingRegex.exec(content)) !== null) {
        const level = match[1].length;
        const text = match[2];
        headings.push({ level, text });
      }
      
      return headings;
    };
    
    const headings = React.useMemo(() => {
      if (type !== "markdown") return [];
      return extractHeadings(content);
    }, [content, type]);

    // 为标题添加锚点
    const addAnchorsToHeadings = (content: string) => {
      return content.replace(
        /^(#{1,6})\s+(.+)$/gm,
        (match, hashes, title) => {
          const id = title
            .toLowerCase()
            .replace(/[^\w\s-]/g, "")
            .replace(/\s+/g, "-");
          return `${hashes} <a id="${id}" class="anchor"></a>${title}`;
        }
      );
    };

    const contentWithAnchors = React.useMemo(() => {
      if (type !== "markdown") return content;
      return addAnchorsToHeadings(content);
    }, [content, type]);

    if (isLoading) {
      return (
        <div className="flex justify-center items-center p-10">
          <Spin tip="加载中..." />
        </div>
      );
    }

    return (
      <div 
        ref={ref} 
        id={id}
        className={`preview-content ${className}`}
      >
        {title && (
          <Title level={2} className="mb-4">
            {title}
          </Title>
        )}

        {taskTitle && (
          <div className="mb-4">
            <Text type="secondary" className="text-sm">
              任务: {taskTitle}
              {stepNumber !== undefined && totalSteps !== undefined && (
                <span className="ml-2">
                  (步骤 {stepNumber}/{totalSteps})
                </span>
              )}
            </Text>
          </div>
        )}

        <div className="markdown-content">
          {type === "markdown" ? (
            <ReactMarkdown
              remarkPlugins={[remarkGfm]}
              rehypePlugins={[rehypeRaw]}
              components={{
                code({ node, inline, className, children, ...props }) {
                  const match = /language-(\w+)/.exec(className || "");
                  return !inline && match ? (
                    <SyntaxHighlighter
                      style={vscDarkPlus}
                      language={match[1]}
                      PreTag="div"
                      {...props}
                    >
                      {String(children).replace(/\n$/, "")}
                    </SyntaxHighlighter>
                  ) : (
                    <code className={className} {...props}>
                      {children}
                    </code>
                  );
                },
                h1: ({ node, children, ...props }) => (
                  <Title level={1} className="mt-6 mb-4" {...props}>
                    {children}
                  </Title>
                ),
                h2: ({ node, children, ...props }) => (
                  <Title level={2} className="mt-5 mb-3" {...props}>
                    {children}
                  </Title>
                ),
                h3: ({ node, children, ...props }) => (
                  <Title level={3} className="mt-4 mb-2" {...props}>
                    {children}
                  </Title>
                ),
                h4: ({ node, children, ...props }) => (
                  <Title level={4} className="mt-3 mb-2" {...props}>
                    {children}
                  </Title>
                ),
                h5: ({ node, children, ...props }) => (
                  <Title level={5} className="mt-2 mb-1" {...props}>
                    {children}
                  </Title>
                ),
                table: ({ node, children, ...props }) => (
                  <div className="overflow-x-auto">
                    <table className="min-w-full divide-y divide-gray-200" {...props}>
                      {children}
                    </table>
                  </div>
                ),
                th: ({ node, children, ...props }) => (
                  <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider" {...props}>
                    {children}
                  </th>
                ),
                td: ({ node, children, ...props }) => (
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500" {...props}>
                    {children}
                  </td>
                ),
                tr: ({ node, children, ...props }) => (
                  <tr className="bg-white even:bg-gray-50" {...props}>
                    {children}
                  </tr>
                ),
                a: ({ node, children, href, ...props }) => (
                  <a 
                    href={href} 
                    className="text-blue-500 hover:text-blue-700 hover:underline" 
                    {...props}
                  >
                    {children}
                  </a>
                ),
                blockquote: ({ node, children, ...props }) => (
                  <blockquote 
                    className="pl-4 border-l-4 border-gray-200 text-gray-700 italic" 
                    {...props}
                  >
                    {children}
                  </blockquote>
                ),
                img: ({ node, src, alt, ...props }) => (
                  <img 
                    src={src} 
                    alt={alt} 
                    className="max-w-full h-auto my-4 rounded-lg" 
                    {...props} 
                  />
                ),
                ul: ({ node, children, ...props }) => (
                  <ul className="list-disc pl-6 my-4" {...props}>
                    {children}
                  </ul>
                ),
                ol: ({ node, children, ...props }) => (
                  <ol className="list-decimal pl-6 my-4" {...props}>
                    {children}
                  </ol>
                ),
                li: ({ node, children, ...props }) => (
                  <li className="my-1" {...props}>
                    {children}
                  </li>
                ),
                p: ({ node, children, ...props }) => (
                  <p className="my-3 leading-relaxed" {...props}>
                    {children}
                  </p>
                ),
                hr: () => <hr className="my-6 border-t border-gray-200" />,
              }}
            >
              {contentWithAnchors}
            </ReactMarkdown>
          ) : (
            <div dangerouslySetInnerHTML={{ __html: content }} />
          )}
        </div>
      </div>
    );
  }
);

PreviewContent.displayName = "PreviewContent";

export default PreviewContent;
